package com.ll.blog.common;

import lombok.Data;

import java.util.ArrayList;
import java.util.List;


/**
 * DFA 算法实现敏感词过滤
 */
@Data
public class WordFilter {
    private List<Word> wordList = new ArrayList<Word>();
    private String regex = "[,./;\"\\\\[{]}}\\'\\*\\(\\)，。；‘【】、{}|、？》《<>\\?&\\^%\\$#]";

    public void build(List<String> words){
        for (String word : words) {
            AddTOTree(wordList,word);
        }
    }

    public static void main(String[] args) {
        WordFilter filter = new WordFilter();
        String[] str = {"aaa","bbb","ccc"};
        filter.build(List.of(str));
//        System.out.println(words);
//        System.out.println(filter.regex);
        boolean b = filter.assertTrue("a..sklsjdskjdaks...a.../a..");
        System.out.println(b);
    }


    public void  AddTOTree(List<Word> list, String str){
        char[] chars = str.toCharArray();
        int i =0;
        for (char c : chars) {
            i++;
            Word word = getWord(list,c);
            if (word ==null){
                word = new Word();
                word.setC(c);
                list.add(word);
                list.sort((a,b)-> a.getC() -b.getC());
            }
            if (word.getNext() == null){
               word.setNext(new ArrayList<Word>());
            }
            word.setIsEnd(i == chars.length);
            list = word.getNext();
        }
    }


    private Word getWord(List<Word> list, char c){
        for (Word word : list) {
            if (word.getC()==c){
                return word;
            }
        }
        return null;
    }

    public boolean assertTrue(String str){
        char[] chars = str.toCharArray();
        int i =0;
        List<Word> words = wordList;
        while (i<chars.length){
            if (skip(chars[i])){
                i++;
                continue;
            }
            Word word = search(words, chars[i]);
            if (word == null) {
                i++;
                words = wordList;
            }else{
                if (word.getIsEnd()){
                    return true;
                }else{
                    i++;
                    words =word.getNext();
                }
            }
        }
        return false;
    }


    /**
     * 二分搜索
     */

    private Word search(List<Word> list , char c){
        if (list.isEmpty()){
            return null;
        }
        int left = 0;
        int right = list.size()-1;
        while (left<=right){
            int target = (left + right) / 2;
            char c1 = list.get(target).getC();
            if( c1== c){
                return list.get(target);
            } else if (c1<c) {
                left = target+1;
            }else {
                right = target-1;
            }
        }
        return null;
    }

    /**
     * 判断字符是否需要跳过
     */
    private boolean skip(char c){
        return String.valueOf(c).matches(regex);
    }


}
